package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        //创建分页构造器
        Page<Category> categoryPage = new Page<>(page,pageSize);
        //创建lmbda 按照sort时间升序排序
        LambdaQueryWrapper<Category> categorylqw =new LambdaQueryWrapper<>();
        categorylqw.orderByAsc(Category::getSort);
        categoryService.page(categoryPage,categorylqw);
        return R.success(categoryPage);
    }

    /**
     *  添加菜品或者套餐
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        boolean save = categoryService.save(category);
        if(save){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    /**
     * 删除菜品或者套餐
     * 注意 相互之间的绑定关系
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.remove(id);
    return R.success("删除成功");
    }

    /**
     *  修改菜品或者菜单
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 菜品分类
     * 根据传回来的属性查询
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //查询类型匹配的
        lqw.eq(category.getType() !=  null, Category::getType,category.getType());
        //根据sort升序  如果一样根据修改时间降序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);

        return R.success(list);
    }
}
